export class Context {
    constructor() {
        this.collections = {
            defaultModel: [],
            ball: [],
        };
        this.repeats = [];
        this.drawables = [];
        this.running = false;
    }
    init(opt={}) {
        this.canvas = opt.canvas || '';
        if (this.canvas) {
            this.ctx2d = this.canvas.getContext('2d');
        }
    }
    addModel(model, collection = this.collections.defaultModel) {
        if (!collection.includes(model)) {
            collection.push(model);
        }
    }
    removeModel(model, collection = this.collections.defaultModel) {
        const index = collection.indexOf(model);
        if (index > -1) collection.splice(index, 1);
    }
    registerRepeat(model) {
        if (!this.repeats.includes(model)) {
            this.repeats.push(model);
        }
    }
    unregisterRepeat(model) {
        const index = this.repeats.indexOf(model);
        if (index > -1) {
            this.repeats.splice(index, 1);
        }
    }
    registerDrawable(model) {
        if (!this.drawables.includes(model)) {
            this.drawables.push(model);
        }
    }
    unregisterDrawable(model) {
        const index = this.drawables.indexOf(model);
        if (index > -1) {
            this.drawables.splice(index, 1);
        }
    }
    start() {
        if (this.running) return;
        this.running = true;
        this.repeat();
    }
    stop() {
        this.running = false;
    }
    repeat() {
        if (this.running) {
            requestAnimationFrame(() => this.repeat());
        }
        this.repeats.forEach(model => model.repeat());
        if (this.ctx2d) {
            this.ctx2d.clearRect(0, 0, this.canvas.width, this.canvas.height);
            this.ctx2d.fillStyle = 'black';
            this.ctx2d.fillRect(0, 0, this.canvas.width, this.canvas.height);
        }
        this.drawables.forEach(model => model.draw(this.ctx2d));
    }
    destroy() {
        this.stop();
    }
}